/**
 * 刷新token
 *
 * @Date 2021/4/20 11:04
 * @author 周世焕
 */

import autoRefresh from 'jwt-autorefresh'

import config from '@/config'

const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

import {getRefreshToken, getToken, setToken, setRefreshToken} from "@/libs/util";
import axios from "@/libs/api.request";

/** Your refresh token mechanism, returning a promise that resolves to the new access tokenFunction (library does not care about your method of persisting tokens) */
const refresh = () => {
    return axios.request({method:'POST',url: baseUrl + '/v1/auth/user/token/refresh',params:{refreshToken:getRefreshToken()}})
        .then(res => {
            setToken(res.data.accessToken)
            setRefreshToken(res.data.refreshToken)
            return res.data.accessToken
        })
}

/** You supply a leadSeconds number or function that generates a number of seconds that the refresh should occur prior to the access token expiring */
const leadSeconds = () => {
    /** Generate random additional seconds (up to 30 in this case) to append to the lead time to ensure multiple clients dont schedule simultaneous refresh */
    const jitter = Math.floor(Math.random() * 30)
    /** Schedule autoRefresh to occur 60 to 90 seconds prior to token expiration */
    return 60 + jitter
}

let start = autoRefresh({ refresh, leadSeconds })

let cancel = () => {}

export function autoRefreshToken(){
    cancel()
    cancel = start(getToken())
}

export function cancelRefresh() {
    cancel()
}
